import * as _ from "lodash";
import CubeForm from "./form";
import CardStore from "../card";
import { spellResourceCondition } from '../../components/excel-layout/cell-field/browser-element/Browser'

export interface LayoutFieldProps {
    fieldid: string;
    isview: string;
    isedit: string;
    ishide: string;
    ismandatory: string;
}
export interface SelectOptionProps {
    cancel: string;
    childitemid: string[];
    docCategory: string;
    id: string;
    isAccordToSubCom: string;
    isdefault: string;
    key: string;
    showname: string;
    maxUploadSize: number;
}
export interface MainFieldProps {
    fieldid: string;
    fieldhtmltype: string;
    fielddbtype: string;
    fieldtype: string;
    fieldlabel: string;
    fieldname: string;

    detail?:string;
    isdetail?:boolean;
    order?:boolean | string;

    placeholder?: string;
    detailtable?: string;
    fieldshowtypes?: string;
    childfieldid?: string;
    expendattr?: string;
    imgheight?: string;
    imgwidth?: string;
    qfws?: string;
    textheight?: string;

    value?: string;
    replaceDatas?: any[];
    options?: SelectOptionProps[];
    uploadData?: any;
}

export const getLayoutFields = (fields1: any, card: CardStore,newParams?:any) => {
    const _fields: string[] = [];
    const labels: any = {};
    const values: any = {};
    const rules: any = {};
    const placeholders: any = {}
    const uploadData: any = {};
    _.each(fields1, (field1: MainFieldProps, fieldName: string) => {
        let formKey: string;
        if (field1.detail) {   //明细表  detailtable之前用的这个参数判断的，取uf_httzgl_dt4 表的最后一个数字，现在走detail的id
            const detailOrderId = field1.detail.split('_')[1];
            const detail = `detail_${detailOrderId}`;
            if (_fields.indexOf(detail) < 0) {
                _fields.push(detail);
                _fields.push(`${detail}[]`);
                _fields.push(`${detail}[].checkbox`);
                _fields.push(`${detail}[].dtl_index`);
                _fields.push(`${detail}[].dtl_id`);
                _fields.push(`deldtlid${detailOrderId}`);
            }
            formKey = `${detail}[].${fieldName}`;
        } else {   //主表
            formKey = fieldName;
            if (field1.replaceDatas && _.isArray(field1.replaceDatas)) {
                let obj =deal4ReplaceDatas(field1.replaceDatas, field1.fieldtype);
                if(field1.fieldtype=='17'){//多人力
                    obj.value=field1.value;
                }
                _.set(values, formKey,obj );
            } else {
                _.set(values, formKey, field1.value||'');
            }
            if (field1.uploadData) {
                _.set(uploadData, formKey, field1.uploadData)
            }

            // 解决#608436 当选择框字段作为标题时，应该显示showname，而非选项的key值
            if (field1.fieldhtmltype === '5' && _.isNumber(Number(field1.value)) && field1.value) {
                // let options: any = field1.options;
                // let obj = {
                //     value: field1.value,
                //     valueSpan: options[Number(field1.value)]&&options[Number(field1.value)].showname||'',
                // }
                // _.set(values, formKey, {...obj, valueObj: obj});
                //#775361 概述：解决了模块基础，页面标题设置复选框字段，当卡片页面选择多个值的时候，值不解析的问题
                let options: any = field1.options;
                let valueArr:any = field1.value.split(',');
                let valueSpan:any = [];
                _.forEach(valueArr, item=>{
                    let have = false;
                    //#873149选择框的选项值和options下标不一定一致，需要通过key来判断
                    _.forEach(options,option=>{
                        if(option.key == Number(item)){
                            valueSpan.push(option.showname);
                            have = true;
                        }
                    })
                    if(!have){
                        valueSpan.push('');
                    }
                    
                })
                let obj:any = {
                    value: field1.value,
                    valueSpan: valueSpan.join(','),
                }
                
                _.set(values, formKey, {...obj, valueObj: obj});
            }
        }
        _fields.push(formKey);
        _.set(labels, formKey, field1.fieldlabel);
        _.set(placeholders, formKey, field1.placeholder);
    })
    try{
        //qc608226概述：表单建模，明细表单，布局中选择了标题没有选择值，卡片页面显示空白
        const etables = newParams['datajson'].eformdesign.etables;
        _.each(etables,(value,key) =>{
            if(key.indexOf("detail_")>-1){
                const detailOrderId = key.split('_')[1];
                const detail = `detail_${detailOrderId}`;
                if (_fields.indexOf(detail) < 0) {
                    _fields.push(detail);
                    _fields.push(`${detail}[]`);
                    _fields.push(`${detail}[].checkbox`);
                    _fields.push(`${detail}[].dtl_index`);
                    _fields.push(`${detail}[].dtl_id`);
                    _fields.push(`deldtlid${detailOrderId}`);
                }
            }
        })
    }catch(e){}
    
    const form = new CubeForm(card, {
        fields: _fields,
        rules,
        labels,placeholders
    });
    form.updateValues(values, fields1 );
    form.setUploadData(uploadData);
    form.isInit = true;
    return form;
}


export const deal4ReplaceDatas = (replaceDatas, fieldtype) => {
    if (fieldtype == '141') {
        const props = replaceDatas.map(d => d.prop);
        return {
            value: spellResourceCondition(props),
            valueObj: props
        }
    }else {
        return {
            value: replaceDatas.map(d => d.id || d.randomFieldId).join(","),
            valueSpan: replaceDatas.map(d => d.name || d.lastname).join(","),
            valueObj: replaceDatas
        }
    }
}